package cn.com.anypay.manager.payment.channel.channeltest1.impl1;

import cn.com.anypay.manager.payment.config.ChannelConfig;
import cn.com.anypay.manager.payment.config.TestChannelConfig;
import cn.com.anypay.manager.payment.core.AbstractPaymentChannelTemplate;
import cn.com.anypay.manager.payment.core.PaymentException;
import cn.com.anypay.manager.payment.core.IPaymentChannelImplementation;
import cn.com.anypay.manager.payment.core.ImplementationMetadata;
import cn.com.anypay.manager.payment.dto.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * 测试渠道1 - 原生实现（impl1）
 *
 * 演示支付渠道抽象框架的使用，通过日志模拟支付流程
 * 使用策略模式，实现具体的支付渠道策略
 *
 * @author AnyPay Team
 * @version 1.0
 * @since 2025-07-05
 */
@Component("channelTest1Impl1PaymentChannelStrategy")
@ImplementationMetadata(
    channelId = ChannelTest1PaymentChannelImpl1Strategy.CHANNEL_ID,
    implementationId = ChannelTest1PaymentChannelImpl1Strategy.IMPLEMENTATION_ID,
    implementationName = ChannelTest1PaymentChannelImpl1Strategy.IMPLEMENTATION_NAME,
    version = "1.0.0",
    description = "测试渠道1的原生实现"
)
public class ChannelTest1PaymentChannelImpl1Strategy extends AbstractPaymentChannelTemplate implements IPaymentChannelImplementation {

    public static final String CHANNEL_ID = "channeltest1";
    public static final String IMPLEMENTATION_ID = "impl1";
    public static final String CHANNEL_NAME = "测试渠道1";
    public static final String IMPLEMENTATION_NAME = "测试渠道1-impl1";
    // 移除静态数组，改用从ProductFactory动态获取

    public ChannelTest1PaymentChannelImpl1Strategy() {
        super();
        // 创建默认配置
        this.channelConfig = new TestChannelConfig(CHANNEL_ID, CHANNEL_NAME);
    }

    public ChannelTest1PaymentChannelImpl1Strategy(ChannelConfig channelConfig) {
        super(channelConfig);
    }

    @Override
    public String getChannelId() {
        return CHANNEL_ID;
    }

    @Override
    public String getChannelName() {
        return CHANNEL_NAME;
    }

    @Override
    public String getImplementationId() {
        return IMPLEMENTATION_ID;
    }

    @Override
    public String[] getSupportedPayProducts() {
        // 使用父类的动态获取方法
        return getSupportedPayProductsFromFactory();
    }

    @Override
    public String getConfigTemplate() {
        return "{\n" +
                "  \"timeout\": 30000,\n" +
                "  \"retryCount\": 3,\n" +
                "  \"logLevel\": \"INFO\",\n" +
                "  \"mockMode\": true,\n" +
                "  \"successRate\": 95,\n" +
                "  \"implementationType\": \"impl1\"\n" +
                "}";
    }

    @Override
    protected void doInitialize() throws PaymentException {
        logger.debug("Initializing channel: {}", getChannelId());
        logger.debug("渠道ID: {}", getChannelId());
        logger.debug("渠道名称: {}", getChannelName());
        logger.debug("实现ID: {}", getImplementationId());
        logger.debug("实现类型: Native/原生实现");
        logger.debug("支持的支付产品: NATIVE, JSAPI, H5");

        // 模拟原生SDK初始化过程
        try {
            Thread.sleep(100); // 模拟初始化耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        logger.debug("=== ChannelTest1-Impl1 初始化完成 ===");
        logger.debug("Channel {} initialized successfully", getChannelId());
    }

    @Override
    protected void doDestroy() {
        logger.debug("=== ChannelTest1-Impl1 销毁开始 ===");
        logger.debug("清理原生SDK资源...");

        // 模拟销毁过程
        try {
            Thread.sleep(50); // 模拟销毁耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        logger.debug("=== ChannelTest1-Impl1 销毁完成 ===");
    }

    @Override
    protected PaymentResultDTO doCreatePayment(PaymentRequestDTO request) throws PaymentException {
        logger.debug("=== ChannelTest1-Impl1 创建支付 ===");
        logger.debug("商户订单号: {}", request.getMerchantOrderId());
        logger.debug("支付金额: {} {}", request.getAmount(), request.getCurrency());
        logger.debug("商品描述: {}", request.getSubject());
        logger.debug("支付产品: {}", request.getPayProduct());

        // 模拟原生SDK支付创建过程
        try {
            Thread.sleep(150); // 原生实现较快
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 原生实现95%成功率
        Integer successRate = channelConfig.getConfigParamAsInteger("successRate");
        if (successRate == null) {
            successRate = 95;
        }

        boolean success = Math.random() * 100 < successRate;
        if (!success) {
            logger.error("支付创建失败 - 模拟失败场景");
            throw new PaymentException("CREATE_FAILED", "支付创建失败", getChannelId());
        }

        // 创建成功结果
        String channelOrderId = "IMPL1_" + UUID.randomUUID().toString().replace("-", "");

        PaymentResultDTO result = PaymentResultDTO.success(request.getMerchantOrderId(), channelOrderId);
        result.setAmount(request.getAmount());
        result.setStatus(PaymentStatusDTO.PENDING);
        result.setCreateTime(new Date());

        // 根据支付产品设置不同的响应数据
        switch (request.getPayProduct()) {
            case "NATIVE":
                result.setQrCode("weixin://wxpay/bizpayurl?pr=" + channelOrderId);
                logger.debug("生成二维码支付: {}", result.getQrCode());
                break;
            case "JSAPI":
                result.setHtmlCode("<script>console.log('JSAPI支付-Impl1');</script>");
                logger.debug("生成JSAPI支付代码");
                break;
            case "H5":
                result.setPayUrl("https://test.payment.com/h5pay?orderid=" + channelOrderId);
                logger.debug("生成H5支付链接: {}", result.getPayUrl());
                break;
        }

        logger.debug("支付创建成功，渠道订单号: {}", channelOrderId);
        return result;
    }

    @Override
    protected QueryResultDTO doQueryPayment(QueryRequestDTO request) throws PaymentException {
        logger.debug("=== ChannelTest1-Impl1 查询支付 ===");
        logger.debug("商户订单号: {}", request.getMerchantOrderId());
        logger.debug("渠道订单号: {}", request.getChannelOrderId());

        // 模拟查询过程
        try {
            Thread.sleep(100); // 原生实现查询较快
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 模拟查询结果
        QueryResultDTO result = QueryResultDTO.success();
        result.setMerchantOrderId(request.getMerchantOrderId());
        result.setChannelOrderId(request.getChannelOrderId());

        // 随机生成支付状态
        double random = Math.random();
        if (random < 0.8) { // 原生实现成功率更高
            result.setStatus(PaymentStatusDTO.SUCCESS);
            result.setPayTime(new Date());
            result.setPaidAmount(new BigDecimal("100.00"));
            logger.debug("支付状态: 成功");
        } else if (random < 0.95) {
            result.setStatus(PaymentStatusDTO.PENDING);
            logger.debug("支付状态: 待支付");
        } else {
            result.setStatus(PaymentStatusDTO.FAILED);
            logger.debug("支付状态: 失败");
        }

        result.setAmount(new BigDecimal("100.00"));
        result.setCurrency("CNY");
        result.setCreateTime(new Date());
        result.setBuyerInfo("测试用户-Impl1");

        logger.debug("查询完成，支付状态: {}", result.getStatus());
        return result;
    }

    @Override
    protected boolean doClosePayment(String orderId) throws PaymentException {
        logger.debug("=== ChannelTest1-Impl1 关闭支付 ===");
        logger.debug("订单号: {}", orderId);

        // 模拟关闭过程
        try {
            Thread.sleep(80); // 原生实现关闭较快
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 原生实现关闭成功率高
        boolean success = Math.random() < 0.98;

        if (success) {
            logger.debug("支付关闭成功");
        } else {
            logger.error("支付关闭失败");
        }

        return success;
    }

    @Override
    protected boolean doVerifyCallback(String data) throws PaymentException {
        logger.debug("=== ChannelTest1-Impl1 验证回调 ===");
        logger.debug("回调数据: {}", data);

        // 模拟签名验证
        if (data == null || data.trim().isEmpty()) {
            logger.error("回调数据为空");
            return false;
        }

        // 原生实现的签名验证逻辑
        boolean valid = data.contains("signature") && data.contains("timestamp") && data.contains("impl1");

        if (valid) {
            logger.debug("回调验证成功");
        } else {
            logger.error("回调验证失败");
        }

        return valid;
    }

    @Override
    protected PaymentResultDTO doProcessCallback(String data) throws PaymentException {
        logger.debug("=== ChannelTest1-Impl1 处理回调 ===");
        logger.debug("回调数据: {}", data);

        // 模拟解析回调数据
        PaymentResultDTO result = PaymentResultDTO.success();
        result.setMerchantOrderId("TEST_ORDER_" + System.currentTimeMillis());
        result.setChannelOrderId("IMPL1_" + UUID.randomUUID().toString().replace("-", ""));
        result.setStatus(PaymentStatusDTO.SUCCESS);
        result.setAmount(new BigDecimal("100.00"));
        result.setPayTime(new Date());
        result.setRawData(data);

        logger.debug("回调处理完成，订单状态: {}", result.getStatus());
        return result;
    }

    @Override
    protected boolean doValidateConfig(String config) {
        logger.debug("=== ChannelTest1-Impl1 验证配置 ===");
        logger.debug("配置内容: {}", config);

        // 简单的配置验证
        if (config == null || config.trim().isEmpty()) {
            logger.error("配置为空");
            return false;
        }

        // 检查必要的配置项
        boolean valid = config.contains("timeout") && config.contains("retryCount");

        if (valid) {
            logger.debug("配置验证通过");
        } else {
            logger.error("配置验证失败");
        }

        return valid;
    }

    @Override
    public void registerProducts(cn.com.anypay.manager.payment.factory.PaymentProductFactory productFactory) {
        logger.debug("=== ChannelTest1-Impl1 注册支付产品 ===");

        try {
            // 注册NATIVE支付产品
            cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.NativePaymentProductStrategy nativeProduct =
                new cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.NativePaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "NATIVE", nativeProduct);

            // 注册JSAPI支付产品
            cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.JSAPIPaymentProductStrategy jsapiProduct =
                new cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.JSAPIPaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "JSAPI", jsapiProduct);

            // 注册H5支付产品
            cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.H5PaymentProductStrategy h5Product =
                new cn.com.anypay.manager.payment.channel.channeltest1.impl1.products.H5PaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "H5", h5Product);

            logger.debug("ChannelTest1-Impl1 支付产品注册完成");
        } catch (Exception e) {
            logger.error("ChannelTest1-Impl1 注册支付产品失败", e);
        }
    }
}